<?php

namespace common\models\shop;

use Yii;
use common\helpers\Utils;
use yii\base\Exception;
use yii\db\Expression;

/**
 * This is the model class for table "{{%shop_cart}}".
 *
 * @property string $id
 * @property string $user_id
 * @property string $goods_id
 * @property string $product_id
 * @property int $num
 * @property string $created_at
 * @property string $updated_at
 * @property int $status
 */
class ShopCart extends \common\db\ActiveRecord {

    CONST STATUS_FINISH = -1;
    CONST STATUS_DELETED = -2;
    CONST STATUS_DEFAULT = 0;
    CONST STATUS_CHECKED = 1;
    CONST STATUS_PREPARE_ORDER = 2;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%shop_cart}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['user_id', 'goods_id', 'product_id', 'num', 'created_at', 'updated_at', 'deleted_at', 'status'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'product_id' => 'Product ID',
            'goods_id' => 'Goods ID',
            'num' => 'num',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'deleted_at' => 'Updated At',
            'status' => 'Status',
        ];
    }

    /**
     * 关联SPU商品
     */
    public function getProduct() {
        return $this->hasOne(ShopProduct::className(), ['id' => 'product_id']);
    }

    /**
     * 关联SKU单品
     */
    public function getGoods() {
        return $this->hasOne(ShopGoods::className(), ['id' => 'goods_id']);
    }

    /**
     * 获取SPU商品名称
     */
    public function getName() {
        $product = $this->product;
        if ($product) {
            return $product->name;
        }
        return '';
    }

    /**
     * 获取SKU单品名称
     */
    public function getSkuAttributes() {
        $goods = $this->goods;
        if (!$goods) {
            return [];
        }
        return [
            'goods_name' => $goods->name,
            'goods_cover' => $goods->picture,
            'goods_code' => $goods->goods_no,
            'goods_price' => $goods->price,
            'goods_discount' => $goods->discount,
        ];
    }

    /**
     * 获取SKUData单品名称
     */
    public function getSkuName() {
        $goods = $this->goods;
        if (!$goods) {
            return '';
        }
        return $goods->name;
    }

    /**
     * SKU单品库存
     */
    public function getStock() {
        return $this->goods ? $this->goods->allowSales : 0;
    }

    /**
     * 是否选中的商品
     */
    public function getChecked() {
        return $this->status == static::STATUS_CHECKED;
    }

    /**
     * 商品是否有效
     */
    public function getIsValid() {
        if (!($this->product && $this->goods)) {
            return false;
        }
        if ($this->stock <= 0) {
            return false;
        }
        return $this->product->status == ShopProduct::STATUS_ACTIVE && $this->goods->status == ShopGoods::STATUS_ACTIVE;
    }

    /**
     * 商品是否有效
     */
    public function getInvalidTips() {
        if (!($this->product && $this->goods)) {
            return '商品已失效';
        }
        if ($this->stock <= 0) {
            return '商品库存不足';
        }
        if ($this->product->status !== ShopProduct::STATUS_ACTIVE) {
            return '商品已下架';
        }
        if ($this->goods->status !== ShopGoods::STATUS_ACTIVE) {
            return '当前规格商品已下架';
        }
        return '';
    }

    public function getGoodsStatus() {
        $goods = $this->goods;
        if ($goods->status != ShopGoods::STATUS_ON) {
            return false;
        } elseif ($this->product_id) {
            $sku = $this->product;
            if ($sku->status != ShopProduct::STATUS_ACTIVE) {
                return false;
            }
        }
        return true;
    }

    public function getPrice() {
        $goods = $this->goods;
        if (!$goods) {
            return 0;
        }
        return $goods->memberPrice;
    }

    public function getOriginalPrice() {
        $goods = $this->goods;
        if (!$goods) {
            return 0;
        }
        return $goods->price * 1;
    }

    public function getDiscount() {
        $goods = $this->goods;
        if (!$goods) {
            return 0;
        }
        return $goods->price - $goods->memberPrice;
    }

    public function getMarketPrice() {
        $goods = $this->goods;
        if (!$goods) {
            return 0;
        }
        if ($goods->price - $goods->memberPrice > 0) {
            return $goods->price * 1;
        }
        return 0;
    }

    /**
     * 清除购物车无效商品
     * @param type $uid
     */
    public static function removeToClean($uid, $ids = []) {
        if (empty($ids)) {
            $query = static::findActive('t')->andWhere([
                't.user_id' => $uid
            ])->innerJoinWith([
                'product p' => function ($q) {
                    $q->active(ShopProduct::STATUS_ACTIVE);
                },
                'goods g' => function ($q) {
                    $q->active(ShopGoods::STATUS_ACTIVE);
                },
            ]);
            $expression = new Expression('`g`.`stock`  + `g`.`shelf` > `g`.`total`');
            $query->andWhere($expression);
            $ids = $query->column();
            return static::deleteAll([
                'and',
                ['not in', 'id', $ids],
                ['user_id' => $uid]
            ]);
        }
        return static::deleteAll([
            'id' => $ids,
            'user_id' => $uid
        ]);
    }

    public static function preparing($uid, $data, &$msg) {
        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            static::updateAll(['status' => self::STATUS_DEFAULT], ['user_id' => $uid]);
            foreach ($data as $id => $num) {
                $cart = static::findOne($id);
                if ($cart == null) {
                    throw new Exception('记录不存在！');
                }
                if ($cart->user_id != $uid) {
                    throw new Exception('您的数据错误！');
                }
                $cart->num = $num;
                $cart->status = self::STATUS_PREPARE_ORDER;
                if (!$cart->save()) {
                    throw new Exception(Utils::arrayToString($cart->getErrors(), true));
                }
            }
            $transaction->commit();
            return true;
        } catch (Exception $e) {
            $transaction->rollBack();
            $msg = $e->getMessage();
            return false;
        }
    }

    /**
     * @param $data
     * 运费计算
     */
    public static function reckonFreight($data, $addressList) {

        $address = current($addressList);
        $ship_fixed = 0; //固定运费
        $ship_template = 0; //模板运费
        $templateIds = [];
        $nums = [];
        foreach ($data as $item) {
            $goods = $item->goods;
            if ($goods->ship_template_id) {
                if (!in_array($goods->ship_template_id, $templateIds)) {
                    $templateIds[$goods->ship_template_id] = $goods->ship_template_id;
                    $nums[$goods->ship_template_id] = $item->num;
                } else {
                    $nums[$goods->ship_template_id] += $item->num;
                }
            } else {
                $ship_fixed += $goods->ship_fee;
            }
        }
        $max_first_price = 0;
        $other_price = [];
        if (!empty($templateIds)) {
            foreach ($templateIds as $key => $id) {
                $template = ShipTemplate::findOne($id);
                if ($address) {
                    Yii::error($address->attributes);
                    $extend = ShipTemplateExtend::find()->where(['like', 'province_names', $address->province])->one();
                    if ($extend) {
                        $template = $extend;
                    }
                }
                $first_price = $template->bynum_sprice;
                if ($first_price > $max_first_price) {
                    $max_first_price = $first_price;
                }
                $other_num = $nums[$key] - $template->bynum_snum;
                Yii::error($template->attributes);
                $other_price[] = ceil($other_num / $template->bynum_xnum) * $template->bynum_xprice;
            }
        }

        $x_price = array_sum($other_price);
        $ship_template = $max_first_price + $x_price;
        return $ship_fixed < $ship_template ? $ship_template : $ship_fixed;
    }

    /**
     * 获取购物车中待结算的商品列表 
     * @param type $uid
     * @return type
     */
    public static function waitBalance($uid, $ids = []) {
        $query = static::findActive('t')->andWhere([
            'and',
            ['>=', 't.status', static::STATUS_CHECKED],
            ['t.user_id' => $uid]
        ])
        ->innerJoinWith([
            'product p' => function ($q) {
                $q->active(ShopProduct::STATUS_ACTIVE);
            },
            'goods g' => function ($q) {
                $q->active(ShopGoods::STATUS_ACTIVE);
            },
        ]);
        $expression = new Expression('`g`.`stock`  + `g`.`shelf` - `g`.`total`');
        $query->andWhere(['<=', 't.num', $expression]);
        if (!empty($ids)) {
            $query->andWhere(['t.id' => $ids]);
        }
        return $query->all();
    }

    public function getThumb() {
        return $this->goods ? $this->goods->thumb : '';
    }

    public static function groupFormat($data) {
        if (empty($data)) {
            return [];
        }
        $result = [];
        foreach ($data as $item) {
            if (!isset($result[$item->product_id])) {
                $result[$item->product_id] = [
                    'id' => $item->product_id,
                    'name' => $item->name,
                    'thumb' => $item->thumb,
                    'checked' => $item->checked,
                    'status' => $item->isValid,
                    'goods' => [],
                ];
            }
//            if (!$item->isValid) {
//                $result[$item->product_id]['status'] = false;
//            }
            $result[$item->product_id]['status'] = true;
            if ($item->checked) {
                $result[$item->product_id]['checked'] = true;
            }
            $result[$item->product_id]['goods'][] = $item;
        }
        return $result;
    }

    /**
     * @inheritdoc
     */
    public function fields() {
        return [
            'id',
            'name',
            'sku' => 'skuName',
            'price',
            'market_price' => 'marketPrice',
            'thumb',
            'stock',
            'product_id',
            'goods_id',
            'num',
            'checked',
            'status' => 'isValid',
        ];
    }

}
